<template>
    <div id="box">
        <!--面包屑区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
   </el-breadcrumb>
   <!--卡片视图区域-->
   <el-card class="box-card">
    <!--搜索和添加区域-->
  <el-row :gutter="20">
  <el-col :span="8">
    <el-input placeholder="请输入内容" v-model="queryinfo.query"  clearable @clear="getUserstlist">
    <el-button slot="append" icon="el-icon-search" @click="getUserstlist">
    </el-button>
  </el-input>
</el-col>
  <el-col :span="4">
<el-button type="primary" @click="addDialogVisiable = true">添加用户</el-button>
</el-col>
</el-row>
<!--表格区域-->
<el-table :data="userslist" :border="true" :stripe="true">
    <el-table-column label="#" type="index"></el-table-column>
    <el-table-column  label="姓名" prop="username"></el-table-column> 
    <el-table-column  label="邮箱" prop="email"></el-table-column> 
    <el-table-column  label="电话" prop="mobile"></el-table-column> 
    <el-table-column  label="角色" prop="role_name"></el-table-column> 
    <el-table-column label="状态"  v-slot="scope">
        <el-switch
  v-model="scope.row.mg_state" @change="userstateChanged(scope.row)">
</el-switch>
    </el-table-column>
    <el-table-column label="操作">
        <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEdit(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="confirm(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" >
  <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
    </el-tooltip>
           
        </template>
    </el-table-column>
</el-table>
<!--分页-->
<el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryinfo.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="queryinfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>

<!--添加用户对话框-->
<el-dialog
  title="添加用户"
  :visible.sync="addDialogVisiable"
  width="50%" @close="addDialogClosed">
  <el-form ref="form" :model="addForm" :rules="addFormRules" label-width="70px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisiable = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<!--修改用户对话框-->
<el-dialog
  title="修改用户信息"
  :visible.sync="editDialogVisiable"
  width="50%" @close="editDialogClosed">
  <el-form ref="editform" :model="editForm" :rules="editFormRules" label-width="70px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>

  <el-form-item label="邮箱" prop="email">
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机" prop="mobile">
    <el-input v-model="editForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisiable = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 定</el-button>
  </span>
</el-dialog>
<!--分配角色对话框-->
<el-dialog
  title="分配角色"
  :visible.sync="fpjsVisible"
  width="50%"
  @close="closea"
  >
  <div>
    <p>当前的用户: {{  usersinfo.username  }}</p>
    <p>当前的角色: {{  usersinfo.role_name  }}</p>
    <p>分配新角色: 
        <el-select placeholder="请选择" v-model="valueID" >
    <el-option
      v-for="item in roleList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
    </p>
  </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="fpjsVisible = false">取 消</el-button>
    <el-button type="primary" @click="fpjs">确 定</el-button>
  </span>
</el-dialog>
    </div>
    </template>

<script>
import { Checkbox } from 'element-ui'
import { async, throwIfEmpty } from 'rxjs'

export default {
    data() {
        //验证邮箱的规则
        var checkEmail = (rule, value, callback) => {
            let reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            if (reg.test(value)) {
                return callback()
            } else {
                callback(new Error("请输入合法邮箱"))
            }
        }
        //验证手机规则
        var checkMobile = (rule, value, callback) => {
            let reg = /^(?:(?:\+|00)86)?1\d{10}$/
            if (reg.test(value)) {
                return callback()
            } else {
                callback(new Error("请输入合法手机号"))
            }
        }
        return {

            //用户列表数据
            userslist: [],
            //参数
            queryinfo: {
                query: '',
                pagenum: 1,
                pagesize: 2
            },
            total: 0,
            //被选中的id值
            valueID: '',
            //控制对话框的显示与隐藏
            addDialogVisiable: false,
            editDialogVisiable: false,
            fpjsVisible: false,
            //添加用户的数据
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            editForm: {},
            //需要分配角色的用户
            usersinfo: {},
            //角色列表
            roleList: [],
            //表单验证
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: "blur" }
                ],
                mobile: [
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator: checkMobile, trigger: "blur" }
                ]

            },
            editFormRules: {
                email: [
                    { required: true, message: "请输入邮箱", trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator: checkMobile, trigger: "blur" }
                ]

            }
        }


    },
    created() {
        this.getUserstlist()
    },
    methods: {
        async getUserstlist() {
            let { data } = await this.$http.get("users", { params: this.queryinfo })
            console.log(data)
            if (data.meta.status !== 200) return this.$message.error("用户列表数据获取失败")
            this.userslist = data.data.users
            this.total = data.data.total
        },
        //每页几条数据事件
        handleSizeChange(news) {
            this.queryinfo.pagesize = news
            this.getUserstlist()
        },
        handleCurrentChange(news) {
            this.queryinfo.pagenum = news
            this.getUserstlist()
        },
        //监听开关状态的改变
        async userstateChanged(users) {
            // console.log(users)
            let { data } = await this.$http.put(`users/${users.id}/state/${users.mg_state}`)
            // console.log(data)
            if (data.meta.status !== 200) return this.$message.error("状态更新失败")
            this.$message.success("状态更新成功")
        },
        //新增对话框关闭事件
        addDialogClosed() {
            this.$refs.form.resetFields()
        },
        //点击确定，添加新用户
        async addUser() {
            this.$refs.form.validate(async (bool) => {
                if (!bool) {
                    return
                }
                let { data } = await this.$http.post('users', this.addForm)
                //  console.log(data)
                if (data.meta.status !== 201) {
                    return this.$message.error("用户添加失败")
                }
                this.$message.success("用户添加成功")
                this.addDialogVisiable = false
                this.getUserstlist()
            })
        },
        //点击修改
        async showEdit(id) {
            let { data } = await this.$http.get(`users/${id}`)
            //   console.log(data)
            if (data.meta.status !== 200) return this.$message.error("修改用户渲染失败")
            this.editForm = data.data
            this.editDialogVisiable = true

        },
        //修改对话框关闭事件
        editDialogClosed() {
            this.$refs.editform.resetFields()
        },
        //点击确定修改用户
        editUser() {
            this.$refs.editform.validate(async (bool) => {
                if (!bool) return false
                let { data } = await this.$http.put("users/" + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
                console.log(data)
                if (data.meta.status !== 200) return this.$message.error("用户修改失败")
                this.$message.success("用户修改成功")
                this.editDialogVisiable = false
                this.getUserstlist()
            })
        },
        //点击删除
        async confirm(id) {
            //如果点确定返回confirm,点取消返回cancel
            let h = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (h !== 'confirm') return this.$message("取消了删除")
            let { data } = await this.$http.delete("users/" + id)
            // console.log(data)
            if (data.meta.status !== 200) return this.$message.error("删除用户失败")
            this.$message.success("删除成功")
            this.getUserstlist()
        },
        //点击分配角色
       async setRole(users) {
            this.usersinfo = users
            //获取角色列表
            let {data}=await this.$http.get("roles")
            // console.log(data)
            if(data.meta.status!==200) return this.$message.error("获取角色列表失败")
            this.roleList=data.data
            this.fpjsVisible = true
        },
        //点击确定。分配角色
       async fpjs(){
          if(!this.valueID) return this.$message.error("请选择需要分配的角色")
       let {data}=await this.$http.put(`users/${this.usersinfo.id}/role`,{rid:this.valueID})
       console.log(data)
       if(data.meta.status!==200) return this.$message.error("角色分配失败")
       this.$message.success("角色分配成功")
       this.fpjsVisible=false
       this.getUserstlist()
         },
         //关闭对话框
         closea(){
        this.valueID=''
         }
    }
}
</script>

<style lang="less" scoped>

</style>